package com.example.recorder716;

import android.annotation.SuppressLint;
import android.app.IntentService;
import android.content.Intent;
import android.media.AudioAttributes;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class RecordService extends IntentService {

    public static final String TAG = "r716_Service";
    public static final String ACTION_START = "com.example.recorder716.action.START";
    public static final String ACTION_STOP = "com.example.recorder716.action.STOP";

    public RecordService() {
        super("RecordService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            Log.i(TAG, "onHandleIntent action:" + action);
            if (ACTION_START.equals(action)) {
                Log.i(TAG, "onHandleIntent start");
                handleActionStart();
            } else if (ACTION_STOP.equals(action)) {
                Log.i(TAG, "onHandleIntent stop");
                doRecord = false;
            }
        }
    }

    private boolean doRecord;

    @SuppressLint("MissingPermission")
    private void handleActionStart() {
        doRecord = true;
        File file = new File(getExternalCacheDir().getAbsolutePath() + "/t1.pcm");
        if (file.exists()) {
            Log.i(TAG, "handleActionStart delete file");
            file.delete();
        }
        try {
            file.createNewFile();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        FileOutputStream fos = null;
        try {
            String path = file.getPath();
            Log.i(TAG, "handleActionStart path:" + path);
            fos = new FileOutputStream(path);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }


        int sr = 16000;
        int bufferSize = AudioRecord.getMinBufferSize(sr, AudioFormat.CHANNEL_IN_MONO,
                AudioFormat.ENCODING_PCM_16BIT);
        AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
        attrBuilder.setUsage(AudioAttributes.USAGE_ASSISTANT);
        attrBuilder.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH);
        attrBuilder.setInternalCapturePreset(MediaRecorder.AudioSource.REMOTE_SUBMIX);
        AudioAttributes attr = attrBuilder.build();

        AudioFormat af = new AudioFormat.Builder()
                .setChannelMask(AudioFormat.CHANNEL_IN_MONO)
                .setEncoding(AudioFormat.ENCODING_PCM_16BIT)
                .setSampleRate(sr)
                .build();
        AudioRecord ar = new AudioRecord(attr, af, bufferSize, AudioManager.AUDIO_SESSION_ID_GENERATE);
        ar.startRecording();

        while (doRecord) {
            byte[] buffer = new byte[bufferSize];
            ar.read(buffer, 0 , bufferSize);
            try {
                fos.write(buffer);
                //Log.i(TAG, "716 write size:" + bufferSize);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        Log.i(TAG, "handleActionStart end.");
        try {
            fos.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}